﻿using FoftmAging.Core;
using Ice.Extension;
using IoTClient.Clients.Modbus;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FoftmAging
{
    public partial class Form1 : Form
    {

        private System.Threading.Timer _countDownTimer;

        private long _agedSecond = 0;

        private Config _config;


        private List<AgingControl> _controls;

        private Dictionary<int, string> _msgDic = new Dictionary<int, string>();


        private string _version = "D20251127";

        private ModbusRtuClient _replyClient;

        private CancellationTokenSource _tokenSource;
        private Task _task;

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            _config = IniHelper.GetConfig();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "软件版本:" + _version;
            InitAgingControls();
        }

        private void InitAgingControls()
        {
            tabControl1.TabPages.Clear();
            var list = _config.GetGroupSettings().Take(_config.GroupCount);
            _msgDic.Clear();
            _controls?.Clear();
            _controls = new List<AgingControl>();
            foreach (var item in list)
            {
                var control = new AgingControl() { Dock = DockStyle.Fill };
                control.Setting = item;
                control.OnMessage += Control_OnMessage;
                var tabPage = new TabPage();
                tabPage.Text = $"{item.GroupNo}组 - {item.PortName}";
                tabPage.Controls.Add(control);
                tabControl1.TabPages.Add(tabPage);

                _msgDic.Add(item.GroupNo, "");


                control.OpenClient();

                _controls.Add(control);
            }
            _replyClient = _controls[0].Client; //默认取第1模块的 串口
        }

        private void Control_OnMessage(int groupNo, string msg)
        {
            _msgDic[groupNo] = msg;

            lock (this)
            {
                var info = string.Join("\r\n", _msgDic.Values);
                lblShow.ShowInfo(info);
            }
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            try
            {
                if (button1.Text == "开始")
                {
                    _agedSecond = 0;
                    _countDownTimer = new System.Threading.Timer(countDownCallback, null, 1000, 1000);

                    //打开
                    _controls.ForEach(x =>
                    {
                        x.OpenClient();
                    });
                    //_replyClient = _controls[0].Client; //默认取第1模块的 串口

                    _tokenSource = new CancellationTokenSource();
                    _task = Task.Run(StartAging); //开始老化



                    button1.Text = "停止";
                    btnConfig.Enabled = false;
                    return;
                }

                //停止

                if (!_task.IsCompleted) //未设置完成通道id
                {
                    _tokenSource.Cancel();
                }
                else
                {

                    _controls.ForEach(x => x.Stop()); //停止

                    //if (_config.IsResetChannel) //需要重置通道id
                    //{
                    //    await Task.Run(() => ResetChnanel());
                    //}

                    //关闭串口
                    //_controls.ForEach(x =>
                    //{
                    //    x.CloseClient();
                    //});

                }

                _countDownTimer?.Dispose();
                _countDownTimer = null;
                button1.Text = "开始";
                btnConfig.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                button1.Enabled = true;
            }


        }

        private void countDownCallback(object state)
        {
            _agedSecond++;
            var timespan = TimeSpan.FromSeconds(_agedSecond);
            lblCountDown.Text = $"{timespan.Hours:D2}:{timespan.Minutes:D2}:{timespan.Seconds:D2}";
        }

        private void btnConfig_Click(object sender, EventArgs e)
        {
            var form = new ConfigForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                _config = IniHelper.GetConfig();
                InitAgingControls();
            }
        }


        /// <summary>
        /// 设置通道
        /// </summary>
        private void StartAging()
        {
            int maxChannelCount = 0;
            var settings = _config.GetGroupSettings();
            maxChannelCount = settings.Take(_config.GroupCount).Max(x => x.ChannelCount);
            lblShow.ShowInfo("正在初始化设备\n请稍等");
            //关闭继电器
            for (int i = 0; i < 32; i++)
            {
                _replyClient.Write(i.ToString(), false, 0, 5);
            }

            Task.Delay(1000);
            for (int i = 1; i <= maxChannelCount; i++)
            {
                //打开继电器
                _replyClient.Write((i - 1).ToString(), true, 0, 5);

                //等待启动时间 设置
                lblShow.ShowInfo($"等待继电器{i}组设备启动");
                Task.Delay(_config.StartupTime * 1000).Wait(_tokenSource.Token);
                var tasks = new List<Task>();
                var id = (byte)i;
                foreach (var ctrl in _controls)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        var ctrl1 = ctrl;
                        ctrl1.SetChannels(id);
                    }));
                }

                Task.WhenAll(tasks).Wait(_tokenSource.Token);

                //设置完成后，关闭继电器
                _replyClient.Write((i - 1).ToString(), false, 0, 5);
            }

            //打开全部继电器
            Task.Delay(2000);
            for (int i = 0; i < maxChannelCount; i++)
            {
                _replyClient.Write(i.ToString(), true, 0, 5);
            }

            //等待设备稳定运行
            Task.Delay(_config.StartupTime * 1000).Wait(_tokenSource.Token);

            //开始 老化
            _controls.ForEach(x =>
            {
                x.Start();
            });
        }

        private void ResetChnanel()
        {
            int maxChannelCount = 0;
            var settings = _config.GetGroupSettings();
            maxChannelCount = settings.Take(_config.GroupCount).Max(x => x.ChannelCount);

            //关闭第1个
            Task.Delay(1000);
            _replyClient.Write("0", false);

            for (int i = 2; i <= maxChannelCount; i++)
            {
                Task.Delay(200);
                var tasks = new List<Task>();
                var id = (byte)i;
                foreach (var ctrl in _controls)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        ctrl.ResetChannels(id);
                    }));
                }

                Task.WhenAll(tasks).Wait(_tokenSource.Token);

                //关闭
                _replyClient.Write((i - 1).ToString(), false, 0, 5);
            }
        }

        /// <summary>
        /// 关闭所有
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSwtichOffAll_Click(object sender, EventArgs e)
        {
            bool b = MessageBox.Show("您是否确定断开全部继电器", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes;
            if (b && _replyClient != null)
            {
                for (int i = 0; i < 32; i++)
                {
                    _replyClient.Write(i.ToString(), false, 0, 5);
                }
            }
        }

        private void btnSwitchOnAll_Click(object sender, EventArgs e)
        {
            bool b = MessageBox.Show("您是否确定吸合全部继电器", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes;
            if (b && _replyClient != null)
            {
                for (int i = 0; i < 32; i++)
                {
                    _replyClient.Write(i.ToString(), true, 0, 5);
                }
            }
        }
    }
}
